<template>
  <div class="user-home">
    <el-card class="user-card">
      <div class="user-info">
        <el-avatar :size="80" :src="userInfo.icon" />
        <div class="info-content">
          <h2>{{ userInfo.nickName }}</h2>
          <p>{{ userInfo.email }}</p>
        </div>
        <el-button 
          v-if="userInfo.isMerchant"
          type="primary" 
          class="enter-shop-btn"
          @click="enterShop"
        >
          <el-icon><Shop /></el-icon>
          进入商铺
        </el-button>
      </div>
      <el-divider />
      <div class="user-stats">
        <div class="stat-item" @click="handleNavigation('UserOrders')">
          <span class="number">{{ userInfo.orderCount }}</span>
          <span class="label">我的订单</span>
        </div>
        <div class="stat-item" @click="handleNavigation('UserFavorites')">
          <span class="number">{{ userInfo.favoriteCount }}</span>
          <span class="label">我的收藏</span>
        </div>
        <div class="stat-item" @click="handleNavigation('UserCoupons')">
          <span class="number">{{ userInfo.couponCount }}</span>
          <span class="label">优惠券</span>
        </div>
      </div>
    </el-card>

    <!-- 功能区域 -->
    <div class="feature-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="feature-card" @click="handleNavigation('UserOrders')">
            <template #header>
              <h3>我的订单</h3>
            </template>
            <div class="order-types">
              <div class="type-item" @click.stop="handleNavigation('UserOrders', { status: 0 })">
                <el-icon><Wallet /></el-icon>
                <span>待付款</span>
              </div>
              <div class="type-item" @click.stop="handleNavigation('UserOrders', { status: 1 })">
                <el-icon><Van /></el-icon>
                <span>待发货</span>
              </div>
              <div class="type-item" @click.stop="handleNavigation('UserOrders', { status: 2 })">
                <el-icon><TakeawayBox /></el-icon>
                <span>待收货</span>
              </div>
              <div class="type-item" @click.stop="handleNavigation('UserOrders', { status: 3 })">
                <el-icon><ChatDotRound /></el-icon>
                <span>待评价</span>
              </div>
              <div class="type-item" @click.stop="handleNavigation('UserAfterSale')">
                <el-icon><Service /></el-icon>
                <span>售后/退款</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="feature-card" @click="handleNavigation('UserFavorites')">
            <template #header>
              <h3>我的收藏</h3>
            </template>
            <div class="favorite-preview">
              <el-empty v-if="!userInfo.favorites?.length" description="暂无收藏商品" />
              <div v-else class="favorite-list">
                <div 
                  v-for="item in userInfo.favorites" 
                  :key="item.id" 
                  class="favorite-item"
                  @click.stop="handleNavigation('GoodsDetail', { id: item.spuId })"
                >
                  <span class="title">{{ item.spuVO?.title }}</span>
                  <span class="price">¥{{ item.spuVO?.price }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="feature-card" @click="handleNavigation('UserCoupons')">
            <template #header>
              <h3>我的优惠券</h3>
            </template>
            <div class="coupon-preview">
              <el-empty v-if="!userInfo.coupons?.length" description="暂无优惠券" />
              <div v-else class="coupon-list">
                <div 
                  v-for="coupon in userInfo.coupons" 
                  :key="coupon.id" 
                  class="coupon-item"
                >
                  <span class="name">{{ coupon.couponData?.name || '优惠券' }}</span>
                  <span class="amount">¥{{ coupon.couponData?.value || 0 }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 账户设置 -->
    <el-card class="settings-section">
      <template #header>
        <h3>账户设置</h3>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="setting-card" @click="handleNavigation('UserSettings', { tab: 'security' })">
            <el-icon><Lock /></el-icon>
            <span>修改密码</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="setting-card" @click="handleNavigation('UserSettings', { tab: 'basic' })">
            <el-icon><User /></el-icon>
            <span>个人资料</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="setting-card" @click="handleNavigation('UserAddress')">
            <el-icon><Location /></el-icon>
            <span>收货地址</span>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock, User, Location, Wallet, Van, TakeawayBox, ChatDotRound, Shop, Service } from '@element-plus/icons-vue'
import { getCookieValue } from '../../utils/request'
import { useUserStore } from '../../stores/modules/user'
import { getUserDashboard } from '../../api/user'
import service from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = ref({
  id: userStore.userInfo?.id || '',
  nickName: getCookieValue('nickName') || '未登录用户',
  email: userStore.userInfo?.email || '未设置邮箱',
  icon: getCookieValue('icon') || '',
  telephone: userStore.userInfo?.telephone || '',
  orderCount: 0,
  favoriteCount: 0,
  couponCount: 0,
  favorites: [],
  coupons: [],
  isMerchant: false
})

// 统一的导航处理方法
const handleNavigation = (routeName, params = {}) => {
  try {
    router.push({
      name: routeName,
      query: params
    })
  } catch (error) {
    console.error('页面跳转失败：', error)
    ElMessage.error('页面跳转失败，请重试')
  }
}

// 加载用户数据
const loadUserData = async () => {
  try {
    const data = await getUserDashboard()
    userInfo.value = {
      ...userInfo.value,
      orderCount: data.orderLenth || 0,
      favoriteCount: data.favoriteLenth || 0,
      couponCount: data.couponLenth || 0,
      favorites: data.rcentFavorite || [],
      coupons: data.recentCoupon || [],
      isMerchant: data.isMerchant || false
    }
  } catch (error) {
    console.error('加载用户数据失败：', error)
    ElMessage.error('加载用户数据失败，请刷新页面重试')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '永久有效'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 检查优惠券是否过期
const isExpired = (expireTime) => {
  if (!expireTime) return false
  return new Date(expireTime) < new Date()
}

// 获取优惠券状态
const getCouponStatus = (coupon) => {
  if (coupon.status === 1) return '已使用'
  if (isExpired(coupon.expireTime)) return '已过期'
  return '可使用'
}

// 进入商铺
const enterShop = () => {
  if (!userInfo.value.isMerchant) {
    ElMessage.warning('您还不是商家，请先申请入驻')
    return
  }
  // 使用完整路径，避免相对路径问题
  window.location.href = '/merchant/dashboard'
}

onMounted(() => {
  loadUserData()
  
})
</script>

<style lang="scss" scoped>
.user-home {
  width: 100%;
}

.user-card {
  margin-bottom: 20px;
}

.user-info {
  position: relative;
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.info-content {
  margin-left: 20px;
}

.info-content h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.info-content p {
  margin: 5px 0 0;
  font-size: 14px;
  color: #909399;
}

.enter-shop-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  padding-top: 20px;
}

.stat-item {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
  }

  .number {
    display: block;
    font-size: 24px;
    color: var(--primary-color);
    font-weight: bold;
  }

  .label {
    color: var(--text-regular);
  }
}

.feature-section {
  margin-bottom: 20px;
}

.feature-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.order-types {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  text-align: center;
}

.type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background-color: var(--primary-color-light);
  }

  .el-icon {
    font-size: 24px;
    color: var(--primary-color);
  }
}

.favorite-preview {
  margin-bottom: 20px;
}

.favorite-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: var(--bg-color);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: var(--primary-color-light);
    transform: translateX(5px);
  }

  .title {
    font-size: 14px;
    color: var(--text-regular);
    flex: 1;
    margin-right: 10px;
  }

  .price {
    font-size: 14px;
    color: var(--primary-color);
    font-weight: bold;
  }
}

.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: var(--bg-color);
  border-radius: 4px;
  cursor: default;
  transition: all 0.3s;

  &:hover {
    background: var(--primary-color-light);
    transform: translateX(5px);
  }

  .name {
    font-size: 14px;
    color: var(--text-regular);
    flex: 1;
    margin-right: 10px;
  }

  .amount {
    font-size: 14px;
    color: var(--primary-color);
    font-weight: bold;
  }
}

.settings-section {
  margin-bottom: 20px;
}

.setting-card {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px;
  border-radius: 4px;
  background: var(--bg-color);
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: var(--primary-color-light);
    transform: translateY(-2px);

    .el-icon {
      color: var(--primary-color);
    }
  }

  .el-icon {
    font-size: 24px;
    color: var(--primary-color);
    transition: color 0.3s;
  }

  span {
    font-size: 14px;
    color: var(--text-regular);
  }
}
</style>